import {getToken, setToken, removeToken} from "@/utils/auth"
import instance from "@/http/"

export default {
  namespaced: true,
  state: {
    token: getToken(),
    roles: [], // 角色
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
  },
  actions: {
    // 用户登录
    login({commit}, userInfo) {
      const {username, password} = userInfo
      return instance({
        url: "/users/login",
        method: "POST",
        data: {
          username,
          password,
        },
      }).then((res) => {
        if (res.data.code == "200") {
          console.log(res.data)
          commit("SET_TOKEN", username)
          setToken(res.data.token)
          return Promise.resolve()
        } else {
          return Promise.reject("用户名或密码错误")
        }
      })
    },
    // 获取用户角色信息
    getInfo({commit, state}) {
      return new Promise((resolve) => {
        setTimeout(() => {
          const roles = state.token === "admin" ? ["admin"] : ["editor"]
          commit("SET_ROLES", roles)
          resolve({roles})
        }, 1000)
      })
    },
    // 重置令牌
    resetToken({commit}) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "")
        commit("SET_ROLES", [])
        removeToken()
        resolve()
      })
    },
  },
}
